from mysql.connector import pooling
from multiprocessing import Process

class DBUtil:
    def __init__(self,poolname="mypool",poolsize=20,dbhost="localhost",dbport="16033",dbuser="root",dbpassword="prs7000.sunri",dbdatabase="checkcorefiles"):
        self.pool = pooling.MySQLConnectionPool(
            pool_name=poolname,
            pool_size=poolsize,
            host=dbhost,
            port=dbport,
            user=dbuser,
            password=dbpassword,
            database=dbdatabase
        )

    def get_conn(self):
        """从连接池获取连接"""
        return self.pool.get_connection()

    def close_conn(self, conn):
        """关闭数据库连接，将连接返回给连接池"""
        if conn:
            conn.close()

    def select_one(self, sql, params=None):
        """查询单条记录"""
        conn = None
        cursor = None
        res = None
        try:
            conn = self.get_conn()
            cursor = conn.cursor(dictionary=True)
            sql = sql.strip() + " limit 1"    # 确保只查询一条记录
            cursor.execute(sql, params)
            res = cursor.fetchone()
        except Exception as err:
            print("查询sql错误：", str(err))
            raise
        finally:
            if cursor:
                cursor.close()
            self.close_conn(conn)
        return res

    def select_all(self, sql, params=None):
        """查询多条记录"""
        conn = None
        cursor = None
        res = None
        try:
            conn = self.get_conn()
            cursor = conn.cursor(dictionary=True)
            cursor.execute(sql, params)
            res = cursor.fetchall()
        except Exception as err:
            print("查询sql错误：", str(err))
            raise
        finally:
            if cursor:
                cursor.close()
            self.close_conn(conn)
        return res

    def uid_db(self, sql, params=None):
        """执行增删改操作"""
        conn = None
        cursor = None
        try:
            conn = self.get_conn()
            cursor = conn.cursor()
            cursor.execute(sql, params)
            conn.commit()
        except Exception as err:
            if conn:
                conn.rollback()
            print("增删改 SQL 执行失败：", str(err))
            raise
        finally:
            if cursor:
                cursor.close()
            self.close_conn(conn)

def worker():
    res = DBUtil().select_one("SELECT * FROM config;")
    print("查询结果为：", res)

    all_res = DBUtil().select_all("SELECT * FROM servers WHERE id = 1;")
    print("所有查询结果为：", all_res)

if __name__ == '__main__':
    pass
    # processes = []
    # for i in range(20):
    #     p = Process(target=worker)
    #     processes.append(p)
    #     p.start()

    # for p in processes:
    #     p.join()

    # xx = select_webhook("目标-240923")
    # print(xx)